<template>
  <el-dialog
    :model-value="props.terminalParamVisible"
    title="系统设置"
    width="55%"
    :before-close="handleClose"
  >
    <div class="terminalParam-form">
      <el-tabs
        v-model="activeName"
        class="demo-tabs"
        style="height: 400px"
        type="border-card"
      >
        <el-tab-pane label="通讯参数" name="first">
          <Communication
            :type="type"
            :loading="loading"
            :position="position"
            @changeData="updateData"
            ref="communicationRef"
          ></Communication>
        </el-tab-pane>
        <el-tab-pane label="终端电能表/交流采样装置参数" name="second">
          <TerminalAmmeter
            :type="type"
            :loading="loading"
            :position="position"
            :randomNumber="randomNumber"
            fromType="setting"
            @changeData="updateData01"
            ref="terminalAmmeterRef"
            width="900px"
          ></TerminalAmmeter>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="dialog-footer">
      <div>
        <template v-if="props.type === '1'">
          表位：<el-select v-model="pos" style="width: 200px">
            <el-option label="1" value="1" />
            <el-option label="5" value="5" />
            <el-option label="9" value="9" />
            <el-option label="13" value="13" />
          </el-select>
        </template>
        <template v-else>
          表位：<el-select v-model="pos" style="width: 200px">
            <el-option :label="position" :value="position" />
          </el-select>
        </template>
      </div>
      <div style="display: flex">
        <div class="opera-btn" v-if="activeName == 'first'">
          <template v-if="props.type != '1'">
            <el-button @click="applyFault">应用已读取的表地址</el-button>
            <el-button type="primary" @click="setFault"> 终端参数 </el-button>
          </template>
          <template v-else>
            <el-button type="primary" @click="handle"> 确定 </el-button>
          </template>
        </div>
        <div class="opera-btn" v-if="activeName == 'second'">
          <template v-if="props.type != '1'">
            <el-button @click="applyFault1">应用已读取的表地址</el-button>
            <el-button type="primary" @click="setFault1"> 终端参数 </el-button>
          </template>
          <template v-else>
            <el-button type="primary" @click="handle"> 确定 </el-button>
          </template>
        </div>
        <el-button @click="handleClose">返回</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { useAppStore, paramsDataStore } from "@/stores";
import { meterPositionPlanSave, meterPositionListTree } from "@/api/app.js";
import {
  meterApplyMeterAddress,
  meterCldParmFalut,
  measuringPointParameterFaultSave,
  meterCommParmFalut,
  meterMeterParamJzq,
  measuringPointParameterMeterParam,
} from "@/api/source.js";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import Communication from "@/components/communication.vue";
import TerminalAmmeter from "@/components/terminalAmmeter.vue";

const useApp = useAppStore();
let { organStructure, currentPlanId } = storeToRefs(useApp);

const emit = defineEmits(["is-show", "doTerminalParameters"]);
const loading = ref(false);
const communicationRef = ref();
const pos = ref("1");
const terminalAmmeterRef = ref();
const props = defineProps({
  terminalParamVisible: Boolean,
  type: String,
  position: {
    type: String,
    default: "",
  },
});
const currentData = ref();
const currentData1 = ref();
const currentData2 = ref();
const activeName = ref("first");
const terId = ref();
const form = reactive({
  planName: "",
  remark: "",
});

onMounted(() => {
  watch(
    props,
    (newValue, oldValue) => {
      if (newValue.type === "2") pos.value = newValue.position;
    },
    { immediate: true },
    { deep: true }
  );
});
const handleClose = () => {
  emit("is-show");
};
//点击确定
const handle = async () => {
  let parm = currentData.value;
  parm.cldList = currentData1.value;
  parm.position = pos.value;
  parm.terId = "";
  let i = 1;
  if (props.type === "1") {
    currentData1.value.forEach((item, index) => {
      if (item.collectorRequestAddress === undefined) {
        item.collectorRequestAddress = currentData2.value[6]["table" + i];
      }
      if (item.requestAddress === undefined) {
        item.requestAddress = currentData2.value[5]["table" + i];
      }
      if (item.requestBaudRate === undefined) {
        item.requestBaudRate = currentData2.value[3]["table" + i];
      }
      if (item.requestPort === undefined) {
        item.requestPort = currentData2.value[2]["table" + i];
      }
      if (item.serialNumber === undefined) {
        item.serialNumber = currentData2.value[0]["table" + i];
      }
      if (item.communicationProtocolType === undefined) {
        item.communicationProtocolType = currentData2.value[4]["table" + i];
      }
      if (item.testPointNumber === undefined) {
        item.testPointNumber = currentData2.value[1]["table" + i];
      }
      i++;
    });
  }
  emit("doTerminalParameters", parm);
};
//更新通讯参数信息
const updateData = (parm) => {
  let arr = {};
  parm.forEach((item) => {
    arr[item.prop] = item.value;
  });
  currentData.value = arr;
  // console.log("updateData", currentData.value);
};
const updateData01 = (parm, parm1, parm2) => {
  currentData1.value = parm;
  currentData2.value = parm1;
  terId.value = parm2;
  // console.log("updateData01", currentData1.value, parm1);
};
//通讯参数-应用已读取的表地址
const applyFault = async () => {
  let parm = {
    pos: props.position,
    planId: currentPlanId.value,
  };
  await meterApplyMeterAddress(parm)
    .then((res) => {
      // console.log(res);
      ElMessage({
        type: "success",
        message: "应用成功",
      });
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        type: "warning",
        message: "应用失败",
      });
    });
};
//终端电能表/交流采样装置参数-应用已读取的表地址
const applyFault1 = async () => {
  let parm = {
    pos: props.position,
    planId: currentPlanId.value,
  };
  await meterApplyMeterAddress(parm)
    .then((res) => {
      // console.log(res);
      ElMessage({
        type: "success",
        message: "应用成功",
      });
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        type: "warning",
        message: "应用失败",
      });
    });
};

//修改测量点通讯参数-设置故障
const setFault = () => {
  if (props.type === "1" || props.type === "2") {
    meterMeterParamJzqApi();
  } else {
    meterCommParmFalutApi();
  }
};
const meterCommParmFalutApi = async () => {
  let parm = JSON.parse(JSON.stringify(currentData.value));
  parm.state = 1;
  parm.pos = Number(props.position);
  parm.planId = currentPlanId.value;
  await meterCommParmFalut(parm)
    .then((res) => {
      // console.log(res);
      ElMessage({
        type: "success",
        message: "设置成功",
      });
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        type: "warning",
        message: "设置失败",
      });
    });
};
const meterMeterParamJzqApi = async () => {
  let parm = JSON.parse(JSON.stringify(currentData.value));
  parm.terId = terId.value;
  parm.pos = Number(props.position);
  parm.planId = currentPlanId.value;
  await meterMeterParamJzq(parm)
    .then((res) => {
      // console.log(res);
      ElMessage({
        type: "success",
        message: "设置成功",
      });
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        type: "warning",
        message: "设置失败",
      });
    });
};
//修改测量点 终端-设置故障
const setFault1 = () => {
  let parm = currentData1.value;
  doSave1(parm);
  doSave2(1);
};
const doSave1 = async (parm) => {
  if (props.type === "1" || props.type === "2") {
    measuringPointParameterMeterParamApi(parm);
  } else {
    measuringPointParameterFaultSaveApi(parm);
  }
};
const measuringPointParameterFaultSaveApi = async (parm) => {
  await measuringPointParameterFaultSave(parm)
    .then((res) => {
      // console.log(res);
      ElMessage({
        type: "success",
        message: "设置成功",
      });
      loading.value = false;
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        type: "warning",
        message: "设置失败",
      });
      loading.value = false;
    });
};
const measuringPointParameterMeterParamApi = async (parm) => {
  await measuringPointParameterMeterParam(parm)
    .then((res) => {
      // console.log(res);
      ElMessage({
        type: "success",
        message: "设置成功",
      });
      loading.value = false;
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        type: "warning",
        message: "设置失败",
      });
      loading.value = false;
    });
};
const doSave2 = async (state) => {
  let parm = {
    pos: Number(props.position),
    planId: currentPlanId.value,
    state,
  };
  await meterCldParmFalut(parm)
    .then((res) => {
      // console.log(res);
      ElMessage({
        type: "success",
        message: "设置成功",
      });
      loading.value = false;
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        type: "warning",
        message: "设置失败",
      });
      loading.value = false;
    });
};
</script>
<style lang="scss" scoped>
.ele-type {
  display: flex;
  .ele-type-item1 {
    width: 390px;
  }
  .ele-type-item2 {
    flex: 1;
  }
}
.dialog-footer {
  display: flex;
  margin: 20px 0px;
  justify-content: space-around;
  .el-button {
    width: 130px;
  }
  .opera-btn {
    margin-right: 20px;
    .el-button {
      width: 150px;
    }
  }
}
</style>
